<?php

namespace app\purchase\logic;
use think\facade\Db;
class PurchaseOrderLogic extends BasicLogic
{

    /**
     * @desc   获取采购订单列表接口
     * @author luckyXiong
     * @date   2024-12-23
     */
    public function index($params=[]){
        $limit             = getIsset($params,'limit',10);
        $spu               = getIsset($params,'spu');
        $purchase_number   = getIsset($params,'purchase_number');
        $track_number      = getIsset($params,'track_number');
        $purchase_status   = getIsset($params,'purchase_status');
        $order_1688_number = getIsset($params,'1688_order_number');
        $account_1688      = getIsset($params,'1688_account');
        $supply_id         = getIsset($params,'supply_id');
        $create_time       = getIsset($params,'create_time');
        $where             = [];

        if($spu){
            $where[] = ['spu', 'like', '%' . $spu . '%'];
        }

        if($track_number){
            $where[] = ['track_info', 'like', '%' . $track_number . '%'];
        }


        if (!empty($create_time)) {
            $where[]  = ['create_time', '>=', date('Y-m-d H:i:s',strtotime($create_time[0]))];
            $where[]  = ['create_time', '<=', date('Y-m-d H:i:s',strtotime($create_time[1]) + 3600*24-1)];
        }

        if($purchase_number){
            $where[] = ['purchase_number', '=',$purchase_number];
        }

        if($order_1688_number){
            $where[] = ['1688_order_number', '=',$order_1688_number];
        }

        if($purchase_status){
            $where[] = ['purchase_status', '=',$purchase_status];
        }


        if($supply_id){
            $where[] = ['supply_id', '=',$supply_id];
        }

        $field = 'purchase_number,spu,sku_nums,purchase_quantity,purchase_cost,supply_id,
                  track_info,purchase_status,create_time,freight,discount_fee,1688_site,
                  1688_remark,1688_order_number,image_url,1688_openUid,1688_wangwang_url,
                  1688_account,purchase_type,operater_id,1688_wangwang_url,1688_submit_status';
        $res   = Db::name('purchase_manual')
            ->field($field)
            ->where($where)
            ->order('create_time desc')
            ->paginate($limit);
        $list = $res->items()?:[];

        //批量获取sku图片;
        $spus          = array_column($list,'spu');
        $supply_ids    = array_column($list,'supply_id');
        $operater_ids  = array_column($list,'operater_id');

        //批量获取创建人;
        $admin_users     = Db::name('system_admin')->field('id,username')->whereIn('id',$operater_ids)->select()->toArray();
        $admin_users_map = array_column($admin_users,null,'id');
        $spu_arr         = [];
        foreach($spus as $v){
            if(strpos($v, ',')){
                $spu_arr = array_merge($spu_arr, explode(',', $v));
            }else{
                $spu_arr[] = $v;
            }
        }
        $supplys      = Db::name('supply')->field('id,supply_name')->whereIn('id',$supply_ids)->select()->toArray();
        $supplys_map  = array_column($supplys,null,'id');
        foreach($list as $k=>$v){
            $supply_names           = $supplys_map[$v['supply_id']]??[];
            $list[$k]['track_info'] = $v['track_info'] ? json_decode($v['track_info'],true):'';
            $list[$k]['supply_name']= $supply_names['supply_name']??'';
            $admin_users_info          = $admin_users_map[$v['operater_id']]??'';
            $list[$k]['operater']      = $admin_users_info['username']??'';
            //货款
            $list[$k]['payment']       = $v['purchase_cost'];
            if($v['discount_fee']){
                $payment               = $v['purchase_cost']-$v['discount_fee'];
                $list[$k]['payment']   = $payment ? getRes($payment) : '0.00';
            }
            if($v['freight']){
                $payment               = $v['purchase_cost'] + $v['freight'];
                $list[$k]['payment']   = $payment ? getRes($payment) : '0.00';
            }

            if($v['discount_fee'] && $v['freight']){
                $payment                = $v['purchase_cost'] + $v['freight']-$v['discount_fee'];
                $list[$k]['payment']    = $payment ? getRes($payment) : '0.00';
            }
            //获取到货和采购数量;
            $arrive_quantity  = self::get_arrive_quantitys($v['purchase_number']);
            $list[$k]['arrive_quantity']     = $arrive_quantity;
            $list[$k]['1688_wangwang_url']   = Config('Logisticskey.1688_info.wangwang_message');
        }

        $data = [
            'list'   => $list,
            'total'  => $res->total(),
        ];
        return  $this->jsonMessage(200,true,'获取成功',$data);
    }


    /**
     * @desc   获取采购人员
     * @author luckyXiong
     * @date   2024-12-21
     */
    public function getPurchaser($params=[]){
        $admin_id = $params['admin_id']??'';
        $info     = Db::name('system_admin')->field('id as operater_id,username')->where('id',$admin_id)->find();
        return  $this->jsonMessage(200,true,'获取成功',$info);
    }


    /**
     * @desc   获取到货数量
     * @author luckyXiong
     * @date   2025-01-10
     */
    private function get_arrive_quantitys($purchase_number){
            $list = Db::name('purchase_manual_detail')->field('id,arrive_quantity,purchase_quantity')->where(['purchase_number'=>$purchase_number])->select()->toArray();
            $arrive_quantity   = array_sum(array_column($list,'arrive_quantity'));
            return $arrive_quantity;
    }





    /**
     * @desc   获取采购人员
     * @author luckyXiong
     * @date   2024-12-21
     */
    public function getPurchaserList($params=[]){
        $username = $params['username']??'';
        $where    = [];
        if($username){
            $username = trim($username);
            $where[] = ['username', 'like', '%' . $username . '%'];
        }
        $where[]  = ['status','=',1];
        $where[]  = ['group_ids','=',24];
        $info     = Db::name('system_admin')->field('id as operater_id,username')->where($where)->select()->toArray();
        return  $this->jsonMessage(200,true,'获取成功',$info);
    }



    /**
     * @desc   草稿箱创建线下直采采购单
     * @author luckyXiong
     * @date   2024-12-21
     */
    public function add_purchase_down($params){
           $is_send        = $params['is_send']??'';
           $is_pass        = $params['is_pass']??'';
           $supply_id      = $params['supply_id']??'';
           $operater_id    = $params['operater_id']??'';
           $track_fee_type = $params['track_fee_type']??'';
           $remark         = $params['remark']??'';
           $remark_color   = $params['remark_color']??'';
           $purchase_detail= $params['purchase_detail']??'';
           $purchase_number= getPurchaseNumber();
           //数据入库;
           $purchase_status= 0;
           if($is_send){ //保存并提交审核;
               $purchase_status =1;
           }

          if($is_pass){ //保存并提交审核;
              $purchase_status =2;
          }
        $purchase_info = [];
        foreach($purchase_detail as $v){
            $spu_info                    = explode('-', $v['seller_sku']);
            $spu                         = $spu_info[0]??'';
            $temp['purchase_number']     = $purchase_number;
            $temp['spu']                 = $spu;
            $temp['seller_sku']          = $v['seller_sku']??'';
            $temp['purchase_price']      = $v['purchase_price']??'';
            $temp['purchase_quantity']   = $v['purchase_quantity']??'';
            $temp['purchase_cost']       = $v['purchase_cost']??'';
            $temp['remark']              = $v['remark']??'';
            $temp['image_url']           = $v['image_url']??'';
            $temp['update_time']         = date('Y-m-d H:i:s',time());
            $temp['create_time']         = date('Y-m-d H:i:s',time());
            $purchase_info[]           = $temp;
        }
        $in_stores_quantity_all = array_sum(array_column($purchase_detail,'purchase_quantity'));
        $purchase_price_all     = array_sum(array_column($purchase_detail,'purchase_price'));
        $current_info = current($purchase_detail);
        //采购主表spu信息统计;
        $spus = array_column($purchase_info,'spu');
        $purchase_arr = [
            'purchase_number'   =>$purchase_number,
            'spu'               =>$spus ? implode(',',$spus):'',
            'sku_nums'          =>count($purchase_detail),
            'purchase_cost'     =>$purchase_price_all,
            'warehouse'         =>'武汉江夏仓',
            'supply_id'         =>$supply_id,
            'purchase_quantity' =>$in_stores_quantity_all,
            'purchase_status'   =>$purchase_status,
            'remark'            =>$remark,
            'remark_color'      =>$remark_color,
            'purchase_type'     =>1,
            'track_fee_type'    =>$track_fee_type??'track_fee_type',
            'operater_id'       =>$operater_id,
            'image_url'         =>$current_info['image_url']??'',
            'update_time'       =>date('Y-m-d H:i:s',time()),
            'create_time'       =>date('Y-m-d H:i:s',time()),
        ];

        try {
            Db::startTrans(); // 开启事务
            Db::name('purchase_manual')->insert($purchase_arr);
            Db::name('purchase_manual_detail')->insertAll($purchase_info);
            Db::commit(); // 提交事务
            return json(DefaultResponse(200, true, '新增成功', ''));
            $this->jsonMessage(200,true,'操作成功',null);
        }
        catch (Exception $e) {
            Db::rollback(); // 回滚事务
            $this->jsonMessage(201,false,$e->getMessage(),null);
        }

    }


    /**
     * @desc   草稿箱创建线下编辑接口
     * @author luckyXiong
     * @date   2024-12-21
     */
    public function edit_purchase_down($params){
        $is_send        = $params['is_send']??'';
        $is_pass        = $params['is_pass']??'';
        $supply_id      = $params['supply_id']??'';
        $operater_id    = $params['operater_id']??'';
        $track_fee_type = $params['track_fee_type']??'';
        $remark         = $params['remark']??'';
        $remark_color   = $params['remark_color']??'';
        $purchase_detail= $params['purchase_detail']??'';
        $purchase_number= $params['purchase_number']??'';
        //数据入库;
        $purchase_status= 0;
        if($is_send){ //保存并提交审核;
            $purchase_status =1;
        }

        if($is_pass){ //保存并通过审核;
            $purchase_status =2;
        }

        foreach($purchase_detail as $v){
            Db::name('purchase_manual_detail')->where(['purchase_number'=>$purchase_number,'seller_sku'=>$v['seller_sku']])->update(
                [
                    'purchase_price'      => $v['purchase_price']??'',
                    'purchase_quantity'   => $v['purchase_quantity']??'',
                    'remark'              => $v['remark']??'',
                    'purchase_cost'       => $v['purchase_cost']??'',
                    'update_time'         => date('Y-m-d H:i:s',time()),
                ]
            );
        }
        $in_stores_quantity_all = array_sum(array_column($purchase_detail,'purchase_quantity'));
        $purchase_price_all     = array_sum(array_column($purchase_detail,'purchase_price'));
        $purchase_arr = [
            'purchase_number'   =>$purchase_number,
            'sku_nums'          =>count($purchase_detail),
            'purchase_cost'     =>$purchase_price_all,
            'warehouse'         =>'武汉江夏仓',
            'supply_id'         =>$supply_id,
            'purchase_quantity' =>$in_stores_quantity_all,
            'purchase_status'   =>$purchase_status,
            'remark'            =>$remark,
            'remark_color'      =>$remark_color,
            'track_fee_type'    =>$track_fee_type??'track_fee_type',
            'operater_id'       =>$operater_id,
            'update_time'       =>date('Y-m-d H:i:s',time()),
        ];

        try {
            Db::startTrans(); // 开启事务
            Db::name('purchase_manual')->where(['purchase_number'=>$purchase_number])->update($purchase_arr);
            Db::commit(); // 提交事务
            $message = '操作成功';
            if($is_send){
                $message = '采购单: '.$purchase_number.'已移入「待审核」状态';
            }
            if($is_pass){
                $message = '采购单: '.$purchase_number.'已移入「待到货」状态';
            }
            $this->jsonMessage(200,true,$message,null);
        }
        catch (Exception $e) {
            Db::rollback(); // 回滚事务
            $this->jsonMessage(201,false,$e->getMessage(),null);
        }

    }





    /**
     * @desc   线下采购单编辑接口详情
     * @author luckyXiong
     * @date   2024-12-21
     */
    public function get_purchase_down($params=[]){
        $purchase_number = $params['purchase_number']??'';
        if(!$purchase_number)  $this->jsonMessage(201,false,'采购单后不能为空!',null);
        $list  = Db::name('purchase_manual_detail')->where('purchase_number',$purchase_number)->select()->toArray();

        $info  = Db::name('purchase_manual')->where('purchase_number',$purchase_number)->find();

        $data = [
            'purchase_type' =>$info['purchase_type'],
            'supply_id'     =>$info['supply_id'],
            'operater_id'   =>$info['operater_id'],
            'track_fee_type'=>$info['track_fee_type'],
            'warehouse'     =>'武汉江夏仓',
            'remark'        => $info['remark'],
            'remark_color'  => $info['remark_color'],
            'sku_nums'      => $info['sku_nums'],
            'purchase_quantity' => $info['purchase_quantity'],
            'purchase_cost'  => $info['purchase_cost'],
            'purchase_detail' => $list,
        ];
        return  $this->jsonMessage(200,true,'获取成功',$data);
    }


    /**
     * @desc   线下采购列表接口
     * @author luckyXiong
     * @date   2024-12-22
     */
    public function getDownPurchase($params=[]){
        $limit           = getIsset($params,'limit',10);
        $spu             = getIsset($params,'spu');
        $purchase_number = getIsset($params,'purchase_number');
        $track_number    = getIsset($params,'track_number');
        $operater_id     = getIsset($params,'operater_id');
        $supply_id       = getIsset($params,'supply_id');
        $create_time     = getIsset($params,'create_time');
        $check_status    = getIsset($params,'check_status');
        $where           = [];

        if($spu){
            $where[] = ['spu', 'like', '%' . $spu . '%'];
        }

        if($track_number){
            $where[] = ['track_info', 'like', '%' . $track_number . '%'];
        }

        if($check_status){
            $where[] = ['check_status', '=', $check_status];
        }

        if (!empty($create_time)) {
            $where[]  = ['create_time', '>=', date('Y-m-d H:i:s',strtotime($create_time[0]))];
            $where[]  = ['create_time', '<=', date('Y-m-d H:i:s',strtotime($create_time[1]) + 3600*24-1)];
        }

        if($purchase_number){
            $where[] = ['purchase_number', '=',$purchase_number];
        }

        if($operater_id){
            $where[] = ['operater_id', '=',$operater_id];
        }

        $where[] = ['purchase_status', '=',0];


        if($supply_id){
            $where[] = ['supply_id', '=',$supply_id];
        }

        $field = 'purchase_number,spu,sku_nums,purchase_quantity,purchase_cost,supply_id,
                  track_info,purchase_status,create_time,operater_id,image_url';
        $res   = Db::name('purchase_manual')
            ->field($field)
            ->where($where)
            ->order('create_time desc')
            ->paginate($limit);
        $list = $res->items()?:[];
        $supply_ids  = array_column($list,'supply_id');
        $supplys      = Db::name('supply')->field('id,supply_name')->whereIn('id',$supply_ids)->select()->toArray();
        $supplys_map  = array_column($supplys,null,'id');
        foreach($list as $k=>$v){
            $supply_names           = $supplys_map[$v['supply_id']]??[];
            $list[$k]['track_info'] = $v['track_info'] ? json_decode($v['track_info'],true):'';
            $list[$k]['supply_name']= $supply_names['supply_name']??'';
        }

        $data = [
            'list'   => $list,
            'total'  => $res->total(),
        ];
        return  $this->jsonMessage(200,true,'获取成功',$data);
    }


    /**
     * @desc   线下采购列表详情接口
     * @author luckyXiong
     * @date   2024-12-22
     */
    public function getDownPurchaseDetail($params=[]){
       $purchase_number  = $params['purchase_number']??'';
       $seller_sku       = $params['seller_sku']??'';
       $create_time      = $params['create_time']??'';
       $limit            = getIsset($params,'limit',10);

        if($seller_sku){
            $where[] = ['seller_sku', 'like', '%' . $seller_sku . '%'];
        }

        if($purchase_number){
            $where[] = ['purchase_number', '=', $purchase_number];
        }


        if (!empty($create_time)) {
            $where[]  = ['create_time', '>=', date('Y-m-d H:i:s',strtotime($create_time[0]))];
            $where[]  = ['create_time', '<=', date('Y-m-d H:i:s',strtotime($create_time[1]) + 3600*24-1)];
        }

        $res   = Db::name('purchase_manual_detail')
            ->field('*')
            ->where($where)
            ->order('create_time desc')
            ->paginate($limit);
        $list = $res->items()?:[];

        $data = [
            'list'   => $list,
            'total'  => $res->total(),
        ];
        return  $this->jsonMessage(200,true,'获取成功',$data);

    }

    /**
     * @desc   线下采购提交审核接口
     * @author luckyXiong
     * @date   2025-01-06
     */
    public function submitDownPurchase($params=[]){
        $purchase_number  = $params['purchase_number']??'';
        Db::name('purchase_manual')->where(['purchase_number'=>$purchase_number])->update(
            [
                  'purchase_status'=> 1,
                  'update_time'    => date('Y-m-d H:i:s',time()),
            ]
        );
        return  $this->jsonMessage(200,true,'操作成功',null);
    }




    /**
     * @desc   编辑运单号接口
     * @author luckyXiong
     * @date   2024-12-23
     */
    public function edit_track_number($params=[]){
           $purchase_number = $params['purchase_number']??'';
           $track_info      = $params['track_info']??'';
           Db::name('purchase_manual')->where(['purchase_number'=>$purchase_number])->update([
                'track_info'   =>json_encode($track_info),
                 'update_time' =>date('Y-m-d H:i:s',time()),
            ]);
        return  $this->jsonMessage(200,true,'操作成功',null);
    }


    /**
     * @desc   获取物流商地址接口
     * @author luckyXiong
     * @date   2024-12-23
     */
    public function get_track_list($params=[]){
        $track_list    = Config('Logisticskey.track_list');
        $search        = $params['keyword']??'';
        $results       = $arr = [];
        if($search){
            foreach ($track_list as $key => $value) {
                if (strpos($value, $search) !== false) {
                    $results[$key] = $value; // 将匹配到的结果存入 $results 数组
                }
            }
        }else{
            $results  = $track_list;
        }

        $info        = getLevel($results);
        foreach($info as $v){
            $arr[] = [
                'value'      => $v['key'],
                'label'      => $v['value'],
            ];
        }
        return  $this->jsonMessage(200,true,'获取成功',$arr);
    }


    /**
     * @desc   获取1688支付账号接口
     * @author luckyXiong
     * @date   2024-12-23
     */
    public function get_1688_account($params=[]){
        $list        = Config('Logisticskey.1688_account');
        $info        = getLevel($list);
        $arr         = [];
        foreach($info as $v){
            $arr[] = [
                'value'      => $v['key'],
                'label'      => $v['value'],
            ];
        }
        return  $this->jsonMessage(200,true,'获取成功',$arr);
    }






    /**
     * @desc   通过审核接口
     * @author luckyXiong
     * @date   2025-01-08
     */
    public function pass_check($params=[]){
        $purchase_number = $params['purchase_number']??'';
        $check_remark    = $params['check_remark']??'';
        $purchase_arr = [
            'purchase_status'   =>2,
            'check_remark'      =>$check_remark,
            'update_time'       =>date('Y-m-d H:i:s',time()),
        ];
        Db::name('purchase_manual')->where(['purchase_number'=>$purchase_number])->update($purchase_arr);
        return  $this->jsonMessage(200,true,'采购单: '.$purchase_number.'  已移入「待到货」状态',null);
    }


    /**
     * @desc   待审核驳回审核接口
     * @author luckyXiong
     * @date   2025-01-08
     */
    public function pass_reject($params=[]){
        $purchase_number = $params['purchase_number']??'';
        $check_remark    = $params['check_remark']??'';
        $purchase_arr    = [
            'purchase_status'   =>0,
            'check_status'      =>2,
            'check_remark'      =>$check_remark,
            'update_time'       =>date('Y-m-d H:i:s',time()),
        ];
        Db::name('purchase_manual')->where(['purchase_number'=>$purchase_number])->update($purchase_arr);
        return  $this->jsonMessage(200,true,'操作成功',null);
    }

    /**
     * @desc   添加采购备注
     * @author luckyXiong
     * @date   2025-01-08
     */
    public function add_remark($params=[]){
        $purchase_number= $params['purchase_number']??'';
        $remark        = $params['remark']??'';
        $remark_color  = $params['remark_color']??'1';

        Db::name('purchase_manual')->where(['purchase_number'=>$purchase_number])->update(
            [
                'remark'      =>$remark,
                'remark_color'=>$remark_color,
            ]
        );
        return  $this->jsonMessage(200,true,'操作成功',null);
    }

    /**
     * @desc   获取待入库的基础信息
     * @author luckyXiong
     * @date   2025-01-08
     */
    public function purchase_insert_info($params=[]){
        $purchase_number= $params['purchase_number']??'';
        $field = 'id,purchase_number,supply_id,purchase_status,sku_nums,track_info,operater_id,create_time';
        $info  = Db::name('purchase_manual')->field($field)->where(['purchase_number'=>$purchase_number])->find();
        //查看当前采购单的状态;
        $purchase_status = $info['purchase_status']??'';
        if($purchase_status && $purchase_status!='2'){
            return  $this->jsonMessage(201,false,'请输入待到货的采购单号',null);
        }

        $supply_name = Db::name('supply')->where('id',$info['supply_id'])->value('supply_name');
        $operater    = Db::name('system_admin')->where('id',$info['operater_id'])->value('username');
        //基础入库信息
        $base_info = [
            'purchase_number'=>$purchase_number,
            'warehouse'      =>'武汉江夏仓库',
            'supply_name'    =>$supply_name ? :'',
            'track_info'     =>$info['track_info'] ? json_decode($info['track_info'],true):'',
            'operater'       =>$operater,
            'create_time'    =>$info['create_time'],
        ];

        $sku_info = Db::name('purchase_manual_detail')->where(['purchase_number'=>$purchase_number])->select()->toArray();
        $spus     = array_column($sku_info,'spu');
        //批量获取图片地址;
        $products     = Db::name('product')->field('spu,product_images')->whereIn('spu',$spus)->select()->toArray();
        $products_map = array_column($products,null,'spu');
        foreach($sku_info as $k=>$v){
            $product_images         = $products_map[$v['spu']]??[];
            $display_images         = $product_images['product_images'] ? current(json_decode($product_images['product_images'])) : '';
            $sku_info[$k]['image_url']  = $display_images;
        }

        $total_nums   = array_sum(array_column($sku_info,'purchase_quantity'));
        $total_arrive = array_sum(array_column($sku_info,'arrive_quantity'));

        $count_info = [
            'sku_nums'   =>$info['sku_nums'],
            'arrive_nums'=>$total_nums - $total_arrive,
        ];


        $list =  [
              'base_info' =>$base_info,
              'count_info'=>$count_info,
              'sku_info'  =>$sku_info,
        ];
        return  $this->jsonMessage(200,true,'操作成功',$list);
    }




    /**
     * @desc   采购变更提交
     * @author luckyXiong
     * @date   2025-01-09
     */
    public function purchase_change_edit($params=[]){
        $purchase_number   = $params['purchase_number']??'';
        $change_reason     = $params['change_reason']??'';
        $remark            = $params['remark']??'';
        $sku_info          = $params['sku_info']??'';
        //查看是否存在;
        $count             = Db::name('purchase_manual_change')->where(['purchase_number'=>$purchase_number])->count();
        $operater_id       = Db::name('purchase_manual')->where(['purchase_number'=>$purchase_number])->value('operater_id');
        switch($count){
            case 0:
                $purchase_change_number = $purchase_number.'C1';
                Db::name('purchase_manual_change')->insert(
                    [
                        'purchase_change_number'=>$purchase_change_number,
                        'purchase_number'       =>$purchase_number,
                        'sku_json'              =>$sku_info   ? json_encode($sku_info):'',
                        'remark'                =>$remark,
                        'change_reason'         =>$change_reason,
                        'operater_id'           =>$operater_id,
                        'create_time'           =>date('Y-m-d H:i:s',time()),
                    ]
                );
                break;
            case 1:
                $purchase_change_number = $purchase_number.'C2';
                Db::name('purchase_manual_change')->insert(
                    [
                        'purchase_change_number'=>$purchase_change_number,
                        'purchase_number'       =>$purchase_number,
                        'sku_json'              =>$sku_info   ? json_encode($sku_info):'',
                        'remark'                =>$remark,
                        'change_reason'         =>$change_reason,
                        'operater_id'           =>$operater_id,
                        'create_time'           =>date('Y-m-d H:i:s',time()),
                    ]
                );
                break;
            case 2:
                $purchase_change_number = $purchase_number.'C3';
                Db::name('purchase_manual_change')->insert(
                    [
                        'purchase_change_number'=>$purchase_change_number,
                        'purchase_number'       =>$purchase_number,
                        'sku_json'              =>$sku_info   ? json_encode($sku_info):'',
                        'remark'                =>$remark,
                        'change_reason'         =>$change_reason,
                        'operater_id'           =>$operater_id,
                        'create_time'           =>date('Y-m-d H:i:s',time()),
                    ]
                );
                break;
            default:
                break;
        }
        return  $this->jsonMessage(200,true,'操作成功',null);
    }


    /**
     * @desc   采购变更提交通过
     * @author luckyXiong
     * @date   2025-01-09
     */
    public function purchase_change_pass($params=[]){
        $purchase_change_number   = $params['purchase_change_number']??'';
        //查看是否存在;
        $info              = Db::name('purchase_manual_change')->where(['purchase_change_number'=>$purchase_change_number])->find();
        $sku_info          = $info['sku_json'] ? json_decode($info['sku_json'],true) :'';

        Db::name('purchase_manual_change')->where('id',$info['id'])->update(
            [
                'purchase_status'=>1,
            ]
        );

        //更新采购单主表;
        $purchase_quantity = array_sum(array_column($sku_info,'new_purchase_quantity'));
        $purchase_cost     = array_sum(array_column($sku_info,'total_purchase_price'));
        Db::name('purchase_manual')->where(['purchase_number'=>$info['purchase_number']])->update(
            [
                'purchase_quantity'=>$purchase_quantity,
                'purchase_cost'    =>$purchase_cost,
                'create_time'      =>date('Y-m-d H:i:s',time()),
            ]
        );
        //更新seller_sku表;
        $purchase_info = [];
        Db::name('purchase_manual_detail')->where(['purchase_number'=>$info['purchase_number']])->delete();
        foreach($sku_info as $v){
            $spu_info                    = explode('-', $v['seller_sku']);
            $spu                         = $spu_info[0]??'';
            $temp['purchase_number']     = $info['purchase_number'];
            $temp['spu']                 = $spu;
            $temp['seller_sku']          = $v['seller_sku']??'';
            $temp['purchase_price']      = $v['new_purchase_price']??'';
            $temp['purchase_quantity']   = $v['new_purchase_quantity']??'';
            $temp['purchase_cost']       = $v['total_purchase_price']??'';
            $temp['image_url']           = $v['image_url']??'';
            $temp['update_time']         = date('Y-m-d H:i:s',time());
            $temp['create_time']         = date('Y-m-d H:i:s',time());
            $purchase_info[]             = $temp;
        }
        Db::name('purchase_manual_detail')->insertAll($purchase_info);
        return  $this->jsonMessage(200,true,'操作成功',null);
    }



    /**
     * @desc   获取待入库的基础信息
     * @author luckyXiong
     * @date   2025-01-08
     */
    public function purchase_change_info($params=[]){
        $purchase_number= $params['purchase_number']??'';
        $field = 'id,purchase_number,supply_id,purchase_type,sku_nums,1688_order_number,track_info,operater_id,create_time';
        $info  = Db::name('purchase_manual')->field($field)->where(['purchase_number'=>$purchase_number])->find();
        $supply_name = Db::name('supply')->where('id',$info['supply_id'])->value('supply_name');
        $operater    = Db::name('system_admin')->where('id',$info['operater_id'])->value('username');
        //基础入库信息
        $base_info = [
            'purchase_number'=>$purchase_number,
            'warehouse'      =>'武汉江夏仓库',
            'supply_name'    =>$supply_name ? :'',
            'purchase_type'  =>$info['purchase_type'],
            '1688_order_number'=>$info['1688_order_number'],
            'operater'       =>$operater,
            'create_time'    =>$info['create_time'],
        ];

        $sku_info = Db::name('purchase_manual_detail')->where(['purchase_number'=>$purchase_number])->select()->toArray();
        $spus     = array_column($sku_info,'spu');
        //批量获取图片地址;
        $products     = Db::name('product')->field('spu,product_images')->whereIn('spu',$spus)->select()->toArray();
        $products_map = array_column($products,null,'spu');
        $arr  = [];
        foreach($sku_info as $k=>$v){
            $product_images                    = $products_map[$v['spu']]??[];
            $display_images                    = $product_images['product_images'] ? current(json_decode($product_images['product_images'])) : '';
            $arr[$k]['image_url']              = $display_images;
            $arr[$k]['seller_sku']             = $v['seller_sku'];
            $arr[$k]['new_purchase_price']     = $v['purchase_price'];
            $arr[$k]['new_purchase_quantity']  = $v['purchase_quantity'];
            $arr[$k]['old_purchase_price']     = $v['purchase_price'];
            $arr[$k]['old_purchase_quantity']  = $v['purchase_quantity'];
        }

        $list =  [
            'base_info' =>$base_info,
            'sku_info'  =>$arr,
        ];
        return  $this->jsonMessage(200,true,'操作成功',$list);
    }


    /**
     * @desc   待到货签收入库接口
     * @author luckyXiong
     * @date   2025-01-08
     */
    public function purchase_insert($params=[]){
        $purchase_number     = $params['purchase_number']??'';
        $sku_info            = $params['sku_info']??'';
        $spus                = [];
        $in_number           = getInNumber();
        //批量获取产品图片信息;
        $seller_skus  = array_column($sku_info,'seller_sku');
        foreach($seller_skus as $v){
            $spu_info = explode('-', $v);
            $spus[]   = $spu_info[0]??'';
        }
        $products     = Db::name('product')->field('spu,product_images')->whereIn('spu',$spus)->select()->toArray();
        $products_map = array_column($products,null,'spu');
        try {
            //更新入库信息表;
            foreach($sku_info as $v){
                $spu_info                    = explode('-', $v['seller_sku']);
                $spu                         = $spu_info[0]??'';
                $temp['in_number']           = $in_number;
                $temp['spu']                 = $spu;
                $temp['seller_sku']          = $v['seller_sku']??'';
                $temp['in_stores_quantity']  = $v['current_quantity']??'1';
                $temp['create_time']         = date('Y-m-d H:i:s',time());
                $in_store_detail[]           = $temp;
                $product_images_info         = $products_map[$spu]??[];
                $current_images              = isset($product_images_info['product_images']) && $product_images_info['product_images'] ? current(json_decode($product_images_info['product_images'],true)) : '';
                Db::name('purchase_manual_detail')->where(['purchase_number'=>$purchase_number,'seller_sku'=>$v['seller_sku']])
                    ->inc('arrive_quantity', $v['current_quantity'])
                    ->update();
                //查看seller_sku是否存在仓库;
                $exist_sku_inventory = Db::name('warehouse_sku_inventory')->where(['seller_sku' => $v['seller_sku']])->find();
                if ($exist_sku_inventory) {
                    Db::name('warehouse_sku_inventory')
                        ->where(['id' => $exist_sku_inventory['id']])
                        ->inc('inventory_quantity',     $v['current_quantity'])
                        ->inc('all_inventory_quantity', $v['current_quantity'])
                        ->update();
                }else {
                    $insert_info = [
                        'spu'                    => $spu,
                        'seller_sku'             => $v['seller_sku'],
                        'product_name'           => $product_info['product_name'] ?? '',
                        'product_images'         => $current_images,
                        'inventory_quantity'     => $v['current_quantity'],
                        'all_inventory_quantity' => $v['current_quantity'],
                        'warehouse'              => '武汉江夏仓',
                        'update_time'            => date('Y-m-d H:i:s', time()),
                        'create_time'            => date('Y-m-d H:i:s', time()),
                    ];
                    Db::name('warehouse_sku_inventory')->insert($insert_info);
                }
            }

            $purchase_info = Db::name('purchase_manual')->field('purchase_number,track_info,operater_id')->where(['purchase_number'=>$purchase_number])->find();
            $in_stores_quantity_all = array_sum(array_column($in_store_detail,'in_stores_quantity'));
            $in_store_arr = [
                'in_number'         =>$in_number,
                'spu'               =>$spus ? current($spus) : '',
                'sku_nums'          =>count($in_store_detail),
                'in_stores_status'  =>2,
                'purchase_number'   =>$purchase_number,
                'operater_id'       =>$purchase_info['operater_id']??'',
                'in_stores_quantity'=>$in_stores_quantity_all
            ];


            $track_info = $purchase_info['track_info']??'';
            $track_numbers = [];
            if($track_info){
                $track_numbers = array_column($track_info,'track_number');
            }

            //签收记录入库;
            $record_log = [
                'purchase_number' =>$purchase_number,
                'track_number'    =>$track_numbers ? current($track_numbers) :'',
                'operater_id'     =>$purchase_info['operater_id']??'',
                'create_time'     =>date('Y-m-d H:i:s', time()),
            ];
            Db::name('warehouse_in_store_record')->insert($record_log);
            Db::name('warehouse_in_store')->insert($in_store_arr);
            Db::name('warehouse_in_store_detail')->insertAll($in_store_detail);
        }
        catch (Exception $e) {
            Db::rollback(); // 回滚事务
            $this->jsonMessage(201,false,$e->getMessage(),null);
        }
        return  $this->jsonMessage(200,true,'操作成功',null);
    }

    /**
     * @desc   取消采购单接口
     * @author luckyXiong
     * @date   2025-01-08
     */
    public function cancel_purchase($params=[]){
        $purchase_number     = $params['purchase_number']??'';
        $cancel_reason       = $params['cancel_reason']??'';
        $cancel_remark       = $params['cancel_remark']??'';
        $cancel_1688         = $params['cancel_1688']??'';
        //变更状态为已取消;
        Db::name('purchase_manual')->where(['purchase_number'=>$purchase_number])->update(
            [
                'purchase_status'      => 4,
                'cancel_reason'        => $cancel_reason,
                'cancel_remark'        => $cancel_remark,
                'update_time'          => date('Y-m-d H:i:s', time()),
            ]
        );

        if($cancel_1688){
            //同步调用取消1688订单接口

        }
        return  $this->jsonMessage(200,true,'操作成功',null);
    }

    /**
     * @desc   终止部分到货接口
     * @author luckyXiong
     * @date   2025-01-08
     */
    public function end_purchase($params=[]){
        $purchase_number     = $params['purchase_number']??'';
        //变更状态为已取消;
        Db::name('purchase_manual')->where(['purchase_number'=>$purchase_number])->update(
            [
                'purchase_status'      =>3,
                'update_time'          =>date('Y-m-d H:i:s', time()),
            ]
        );
        return  $this->jsonMessage(200,true,'操作成功',null);
    }



}